package org.webscale.util.scripts;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Properties;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;
import org.webscale.ApplicationController;
import org.webscale.ApplicationException;



public abstract class BaseSequentialScript implements Script {
	private static final Logger log = Logger.getLogger(BaseSequentialScript.class);
	int count = 0;
	long sleepTime = 0;
	File errorFile = new File("not_processed.txt");
	private static boolean  propLoaded = false;
	private static Properties properties = null;

	public static String propertiesFileLocation = "application.properties";
	
	public BaseSequentialScript(){
		super();
	}
	
	
	

	public void execute() {
		execute(new InstrumentationCallback() {
		
			public void onLineItemSuccess(Script script) {
				count++;
				log.info("Processing line-" + count);
				if (getSleepTime() > 0) {
					sleep(getSleepTime());
				}
			}

		
			public void beforeFirstLineItem(Script script) {
			}

		
			public void afterLastLineItem(Script script) {
				log.info("FINSISHED -" + count);
			}

	
			public void onLineItemFailure(Script script) {
				
			}
		});
	}

	public long getSleepTime() {
		return sleepTime;
	}

	public void setSleepTime(long sleepTime) {
		this.sleepTime = sleepTime;
	}
	
	protected void writeToTextFile(File file, String html) throws IOException {
		if (file == null) {
			throw new IllegalArgumentException("File should not be null.");
		}

		Writer output = new BufferedWriter(new FileWriter(file));
		// FileWriter always assumes default encoding is OK!
		output.write(html);
		output.close();
	}

	

	
	protected String getHTTPPageForURL(String url) throws HttpException,
			IOException {
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(url);
		// Provide custom retry handler is necessary
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(3, false));
		method.setFollowRedirects(true);
		// Execute the method.
		int statusCode = client.executeMethod(method);
		if (statusCode != HttpStatus.SC_OK) {
			System.err.println("Method failed: " + method.getStatusLine());
		}
		byte[] responseBody = method.getResponseBody();
		return new String(responseBody);
	}

	protected void sleep(long ms) {
		try {
			Thread.currentThread().sleep(ms);
		} catch (InterruptedException e) {
			log.warn("Error while sleep ", e);
		}
	}
	
	protected void loadSpring() {
		if (!propLoaded)
			loadProp();
		if (ApplicationController.instance().isRunning())
			return;
		try {
			String mode = properties.getProperty("application-run-mode");
			if(mode == null){
				mode = "test";
				properties.setProperty("application-run-mode", mode);
			}
			ApplicationController.instance().setStartUpParamenters(properties);
			ApplicationController.instance().init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	private void loadProp() {
		if (properties == null) {
			InputStream is = BaseSequentialScript.class.getClassLoader()
					.getResourceAsStream(propertiesFileLocation);
	//		logger.debug(propertiesFileLocation);
	//		logger.debug(" IS is " + is);
			try {
				properties = new Properties();
				properties.load(is);
				propLoaded = true;
			} catch (Exception e) {
				e.printStackTrace();
				throw new ApplicationException(e);
			}
		}
	}
	

}
